﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using Microsoft.Practices.Unity;
using WebShop.Contracts;
using WebShop.DAL.Interfaces;
using Webdiyer.WebControls.Mvc;

namespace WebShop.DAL.Repositories
{
    public class OrderRepository : IOrderRepository
    {
        [Dependency]
        public NWData Db { get; set; }

        public void Create(Order objectToCreate)
        {
            Db.DataContext.Orders.Add(objectToCreate);
        }

        public void Delete(int id)
        {
            Order o = Get(id);
            o.Order_Details.Clear();
            Db.DataContext.Entry(o).State = EntityState.Deleted;
        }

        public void Edit(Order objectToUpdate)
        {
            Db.DataContext.Entry(objectToUpdate).State = EntityState.Modified;
        }

        public Order Get(int id)
        {
            return Db.DataContext.Orders.Include(p => p.Order_Details).FirstOrDefault(o => o.OrderID == id);
        }

        public Order Find(System.Linq.Expressions.Expression<Func<Order, bool>> predicate)
        {
            return Db.DataContext.Orders.SingleOrDefault(predicate);
        }

        public IEnumerable<Order> List()
        {
            return Db.DataContext.Orders.ToList();
        }

        public PagedList<Order> List(int? page, int pageSize)
        {
            return Db.DataContext.Orders.ToPagedList(page.GetValueOrDefault(1), pageSize);
        }

        public PagedList<Order> FindList(int? page, int pageSize, System.Linq.Expressions.Expression<Func<Order, bool>> predicate = null, System.Linq.Expressions.Expression<Func<Order, string>> orderBy = null, bool ascending = true)
        {
            var query = Db.DataContext.Orders.Include(p => p.Shippers).Include(p => p.User).Include(p => p.Order_Details);

            if (predicate != null)
            {
                query = query.Where(predicate);
            }

            if (orderBy != null)
            {
                if (ascending)
                {
                    query = query.OrderBy(orderBy);
                }
                else
                {
                    query = query.OrderByDescending(orderBy);
                }
            }
            else
            {
                query = query.OrderByDescending(e => e.OrderDate);
            }

            return query.ToPagedList(page.GetValueOrDefault(1), pageSize);
        }

        public void Detach(Order objectToDetach)
        {
            Db.DataContext.Entry(objectToDetach).State = EntityState.Detached;
        }

        public void SaveChanges()
        {
            Db.DataContext.SaveChanges();
        }

        /*public void CreateOrderDetail(Order_Detail detail)
        {
            _db.DataContext.Order_Details.Add(detail);
        }*/
    }
}